package com.freexiaoyu.cloud.ui.base;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public abstract class BaseBindingAdapter<T, B extends ViewDataBinding> extends RecyclerView.Adapter<BaseBindingAdapter.ViewHolder<B>> {

    protected List<T> items;
    private OnItemClickListener<T> onItemClickListener;

    public BaseBindingAdapter(List<T> items) {
        this.items = items;
    }

    @NonNull
    @Override
    public ViewHolder<B> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        B binding = DataBindingUtil.inflate(
                LayoutInflater.from(parent.getContext()),
                getLayoutResId(),
                parent,
                false
        );
        return new ViewHolder<>(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder<B> holder, int position) {
        T item = items.get(position);
        bindItem(holder.binding, item);

        // 设置点击事件
        holder.binding.getRoot().setOnClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onItemClick(item, position);
            }
        });

        holder.binding.executePendingBindings();
    }

    @Override
    public int getItemCount() {
        return items == null ? 0 : items.size();
    }


    // 追加单个数据项
    public void addItem(T item) {
        if (item != null) {
            items.add(item);
            notifyItemInserted(items.size() - 1); // 通知插入了一个新项
        }
    }

    // 追加多个数据项
    public void addItems(List<T> newItems) {
        if (newItems != null && !newItems.isEmpty()) {
            int startPosition = items.size();
            items.addAll(newItems);
            notifyItemRangeInserted(startPosition, newItems.size()); // 通知插入了一系列新项
        }
    }

    protected abstract int getLayoutResId();

    protected abstract void bindItem(B binding, T item);

    // 设置点击监听器
    public void setOnItemClickListener(OnItemClickListener<T> listener) {
        this.onItemClickListener = listener;
    }

    // 点击事件接口定义
    public interface OnItemClickListener<T> {
        void onItemClick(T item, int position);
    }

    // ViewHolder 持有泛型 Binding
    static class ViewHolder<B extends ViewDataBinding> extends RecyclerView.ViewHolder {
        B binding;

        public ViewHolder(B binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}